package member

import (
	"net/http"

	"fmt"

	"awfan.cn/utils"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func query(format, id string, w http.ResponseWriter, db *mgo.Database) {
	if !bson.IsObjectIdHex(id) {
		utils.WriteError(format, 405, fmt.Sprintf("#id is wrong format: '%v'", id), w)
		return
	}

	c := db.C(utils.PkgName(MEMBER_XML{}))

	q := c.FindId(bson.ObjectIdHex(id))

	var count int
	var err error

	if count, err = q.Count(); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	if count <= 0 {
		utils.WriteError(format, 402, "#account not exist", w)
		return
	}
	var data = MEMBER_XML{}

	if err := q.One(&data); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	data.Token = ""
	data.Password = "******"

	var url string
	if url, err = utils.ToImageFile(data.Id.Hex(), data.Image); err != nil {
		utils.WriteError(format, 404, err.Error(), w)
		return
	}

	data.Image = url

	utils.WriteData(format, data, w)
}

func teacher(format string, school string, w http.ResponseWriter, db *mgo.Database) {
	c := db.C(utils.PkgName(MEMBERS_XML{}))

	if !bson.IsObjectIdHex(school) {
		utils.WriteError(format, 404, fmt.Sprintf("school id is wrong format '%v'", school), w)
		return
	}

	v := MEMBERS_XML{}

	err := c.Find(bson.M{"school.id": school, "role": "t"}).All(&v.Members)

	if err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	for index, d := range v.Members {
		v.Members[index].Password = "******"
		v.Members[index].Token = ""

		var url string
		if url, err = utils.ToImageFile(d.Id.Hex(), d.Image); err != nil {
			continue
		}

		v.Members[index].Image = url
	}
	utils.WriteData(format, v, w)
}

func student(format string, id string, w http.ResponseWriter, db *mgo.Database) {
	c := db.C(utils.PkgName(MEMBERS_XML{}))

	if !bson.IsObjectIdHex(id) {
		utils.WriteError(format, 404, fmt.Sprintf("id id is wrong format '%v'", id), w)
		return
	}

	v := MEMBERS_XML{}

	err := c.Find(bson.M{"parent.id": id, "role": "s"}).All(&v.Members)

	if err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	for index, d := range v.Members {
		v.Members[index].Password = "******"
		v.Members[index].Token = ""

		var url string
		if url, err = utils.ToImageFile(d.Id.Hex(), d.Image); err != nil {
			continue
		}

		v.Members[index].Image = url
	}

	utils.WriteData(format, v, w)
}
